package com.hhs.storage.config.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hhs.storage.bean.JxcMenu;
import com.hhs.storage.bean.JxcRole;
import com.hhs.storage.bean.User;
import com.hhs.storage.service.JxcMenuService;
import com.hhs.storage.service.RoleService;
import com.hhs.storage.service.UserService;
import com.hhs.storage.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    @Resource
    JxcMenuService jxcMenuService;

    @Resource
    RoleService roleService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User)SecurityUtils.getSubject().getSession().getAttribute("user");
        Map<String, Object> map = roleService.getByUserId(user.getId());
        List<JxcRole> list = ( List<JxcRole> )map.get("data");
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        for (JxcRole jxcRole : list) {
            log.debug("角色："+jxcRole.getFlag());
            sai.addRole(jxcRole.getFlag());
        }
        return sai;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken ut = (UsernamePasswordToken)token;
        String account = ut.getUsername();

        User user = userService.selectOne(new EntityWrapper<User>().eq("account_", account));
        if(user == null){
            throw new UnknownAccountException("用户不存在");
        }

        try {
            //查询到用户后，关联查询该用户的菜单，存入session中
            List<JxcMenu> menulist = jxcMenuService.findByUserId(user.getId());
            menulist =  JxcMenu.formatMenu(menulist);
            SecurityUtils.getSubject().getSession().setAttribute("menulist",menulist);
            SecurityUtils.getSubject().getSession().setAttribute("user",user);
            System.out.println(menulist);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ShiroException("菜单解析失败");
        }

//         密码MD5加盐加密
         ByteSource byteSource=ByteSource.Util.bytes(account);//取盐值
         SimpleAuthenticationInfo si = new SimpleAuthenticationInfo(account, Md5Util.getMD5(user.getPassword(),account),byteSource,getName());
         return si;
    }
}
